<?php

class AmigosController extends Controller
{
	/**
	 * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
	 * using two-column layout. See 'protected/views/layouts/column2.php'.
	 */
	public $layout='//layouts/column2';

	/**
	 * @return array action filters
	 */
	public function filters()
	{
		return array(
			'accessControl', // perform access control for CRUD operations
			'postOnly + delete', // we only allow deletion via POST request
		);
	}

	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules()
	{
		return array(
			array('allow',  // allow all users to perform 'index' and 'view' actions
				'actions'=>array('index','view'),
				'users'=>array('*'),
			),
			array('allow', // allow authenticated user to perform 'create' and 'update' actions
				'actions'=>array('create','update','veramigos','eliminaramistad','verperfil','getNombreAmigo'),
				'users'=>array('@'),
			),
			array('allow', // allow admin user to perform 'admin' and 'delete' actions
				'actions'=>array('admin','delete'),
				'users'=>array('admin'),
			),
			array('deny',  // deny all users
				'users'=>array('*'),
			),
		);
	}

	/**
	 * Displays a particular model.
	 * @param integer $id the ID of the model to be displayed
	 */
	public function actionView($id)
	{
		$this->render('view',array(
			'model'=>$this->loadModel($id),
		));
	}

	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionCreate()
	{
		$model=new Amigos;

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['Amigos']))
		{
			$model->attributes=$_POST['Amigos'];
			if($model->save())
				$this->redirect(array('view','id'=>$model->idusuario));
		}

		$this->render('create',array(
			'model'=>$model,
		));
	}

	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'view' page.
	 * @param integer $id the ID of the model to be updated
	 */
	public function actionUpdate($id)
	{
		$model=$this->loadModel($id);
		$model2= new Amigos;

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['Amigos']))
		{
			$model->attributes=$_POST['Amigos'];
			$model2->idusuario=$model->idamigo;
			$model2->idamigo=$model->idusuario;
			if($model->save() && $model2->save()){
				$this->redirect(array('view','id'=>$model->idusuario));
				}
		}

		$this->render('update',array(
			'model'=>$model,
		));
	}

	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'admin' page.
	 * @param integer $id the ID of the model to be deleted
	 */
	public function actionDelete($id)
	{
		$this->loadModel($id)->delete();

		// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
		if(!isset($_GET['ajax']))
			$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
	}

	
	
	
	public function actionVerperfil($idamigo){
	
	
	$model=new Comentarios;

		
		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);
		$count=Yii::app()->db->createCommand('SELECT COUNT(*) FROM comentarios WHERE idmurousuario='.$idamigo)->queryScalar();
		$sql='SELECT usuarios.nombre, comentarios.comentario, comentarios.fecha, idcomentario, idfoto FROM comentarios 
		JOIN usuarios ON usuarios.idusuario=comentarios.idusuario		
		WHERE idmurousuario='.$idamigo.' ORDER BY fecha';
	$dataProvider=new CSqlDataProvider($sql, array(
			'keyField'=>'idcomentario',
			'totalItemCount'=>$count,
			'sort'=>array(
				'attributes'=>array(
					'idcomentario','nombre', 'comentario','fecha','idfoto'
				),
			),
			'pagination'=>array(
				'pageSize'=>50,
			),
		));
		if(isset($_POST['Comentarios']))
		{
			
			$model->attributes=$_POST['Comentarios'];
			$model->idmurousuario=$idamigo; //0 significa que lo escribi en mi muro!
			$model->idfoto=0; // 0 significa que no lo escribi en ninguna foto, es decir que lo puse en mi muro!
			$model->fecha=date('Y-m-d H:i:s');
			$model->idusuario=Yii::app()->session['idusuario'];
			$model->save();
			//if($model->save())
			//	$this->render('verperfil',array('model'=>$model,'data'=>$dataProvider,'idamigo'=>$model->idmurousuario,));
		}
		$amigo=Usuarios::model()->findByPk($idamigo);
		$this->render('verperfil',array('model'=>$model,'data'=>$dataProvider,'amigo'=>$amigo,));
	
	}
	
	
	
	
	public function getNombreAmigo($idamigo){
		$modelo=new Amigos;
		return $modelo->getNombreAmigo($idamigo);	
	}
	
	
	
	
	public function actionEliminaramistad($idamigo)
	{
		$modelo=Amigos::model()->find('idamigo=? AND idusuario=?',array($idamigo,Yii::app()->session['idusuario']));
		$modelo2=Amigos::model()->find('idusuario=? AND idamigo=?',array($idamigo,Yii::app()->session['idusuario']));
		$modelo->delete();
		$modelo2->delete();
		//$this->loadModel($id)->delete();
		
		// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
		if(!isset($_GET['ajax']))
			$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('veramigos'));
	}
	
	/*
	public function actionEliminaramistad($id)
	{
		$this->loadModel($id)->delete();

		// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
		if(!isset($_GET['ajax']))
			$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('veramigos'));
	}*/
	
	
	
	
	/**
	 * Lists all models.
	 */
	public function actionIndex()
	{
		$dataProvider=new CActiveDataProvider('Amigos');
		$this->render('index',array(
			'dataProvider'=>$dataProvider,
		));
	}

	
	public function actionVerAmigos()	
	{
		
	
	$count=Yii::app()->db->createCommand('SELECT COUNT(*) FROM amigos WHERE idusuario='.Yii::app()->session['idusuario'])->queryScalar();
	
	
	$sql='SELECT idamigo,usuarios.nombre,usuarios.apellido 
	    FROM amigos
		JOIN usuarios ON usuarios.idusuario=amigos.idamigo
		WHERE amigos.idusuario='.Yii::app()->session['idusuario'];
	
	
	
	$dataProvider=new CSqlDataProvider($sql, array(
		'keyField'=>'idamigo',
		'totalItemCount'=>$count,
		'sort'=>array(
			'attributes'=>array(
				'idamigo', 'nombre', 'apellido',
			),
		),
		'pagination'=>array(
			'pageSize'=>25,
		),
	));
	
		$this->render('veramigos',array('model'=>$dataProvider,));
	}
	
	
	
	/**
	 * Manages all models.
	 */
	public function actionAdmin()
	{
		$model=new Amigos('search');
		$model->unsetAttributes();  // clear any default values
		if(isset($_GET['Amigos']))
			$model->attributes=$_GET['Amigos'];

		$this->render('admin',array(
			'model'=>$model,
		));
	}
	
	
	
	
	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer $id the ID of the model to be loaded
	 * @return Amigos the loaded model
	 * @throws CHttpException
	 */
	public function loadModel($id)
	{
		$model=Amigos::model()->findByPk($id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}

	/**
	 * Performs the AJAX validation.
	 * @param Amigos $model the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='amigos-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}
}
